const down = fileUrl => {
  const id = 'for_download_iframe'
  let $f = document.getElementById(id)
  if (!$f) {
    $f = document.createElement('iframe')
    document.body.appendChild($f)
  }
  $f.id = id
  $f.setAttribute('src', fileUrl)
  $f.style.display = 'none'
}
const aDown = (url, name) => {
  const id = 'down_' + Math.random()
  const $f = document.createElement('a')
  $f.id = id
  $f.href = `${url}?rna=${name}&dl=1`
  $f.target = '_blank'
  $f.style.display = 'none'
  document.body.append($f)
  $f.click()
  $f.remove()
}
// 最终版，解决无法下载txt的问题
const iframeDown = (url, name) => {
  const id = 'for_download_iframe'
  let $f = document.getElementById(id)
  if (!$f) {
    $f = document.createElement('iframe')
    document.body.appendChild($f)
  }
  $f.id = id
  $f.setAttribute('src', `${url}?rna=${name}&dl=1`)
  $f.style.display = 'none'
}
const postDown = (fileUrl, datas) => {
  return new Promise((resolve, reject) => {
    const id = 'for_download_iframe'
    let $f = document.getElementById(id)
    if (!$f) {
      $f = document.createElement('iframe')
      document.body.appendChild($f)
    }
    const $form = document.createElement('form')
    $form.action = fileUrl
    $form.method = 'POST'
    for (const key in datas) {
      const tmp = document.createElement('input')
      tmp.name = key
      tmp.value = datas[key]
      $form.appendChild(tmp)
    }
    $f.contentDocument.body.appendChild($form)
    $f.style.display = 'none'
    $f.onload = () => {
      try {
        const { code } = JSON.parse($f.contentDocument.body.innerHTML)
        if (code !== '401') {
          resolve()
        } else {
          reject(code)
        }
      } catch (err) {
        reject('404')
      }
    }
    setTimeout(resolve, 1000)
    $app.$nextTick(() => {
      $form.submit()
    })
  })
}
// 下载文件流
const downloadFile = (data, type, fileName) => {
  const blob = new Blob([data], { type: `application/${type};charset=utf-8` })
  // 获取heads中的filename文件名
  const downloadElement = document.createElement('a')
  // 创建下载的链接
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  // 下载后文件名

  const formatString = escape(fileName)
  // 再使decodeURI对其解码
  downloadElement.download = decodeURI(formatString)
  document.body.appendChild(downloadElement)
  // 点击下载
  downloadElement.click()
  // 下载完成移除元素
  document.body.removeChild(downloadElement)
  // 释放掉blob对象
  window.URL.revokeObjectURL(href)
}
export default {
  down,
  aDown,
  postDown,
  iframeDown,
  downloadFile
}
